package com.jiaquyun.jcps.mode

import com.jiaquyun.jcps.app.BaseApplication
import com.jiaquyun.jcps.entity.ArticleResponse
import com.jiaquyun.jcps.entity.ConfigResponse
import com.jiaquyun.jcps.entity.PhotoResponse
import com.jiaquyun.jcps.mode.api.AccessApi
import com.lemlin.network.HttpServiceData
import com.lemlin.network.HttpServiceManager
import com.lemlin.network.HttpServiceSubscribe
import com.lemlin.network.SubscribeListener
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import top.zibin.luban.Luban

open class BaseManager : HttpServiceManager<BaseApi>(BaseApi::class.java)  {

    /**
     * 上传图片
     * */
    fun uploadImage(path: String, listener: SubscribeListener<PhotoResponse>): Disposable =
        subscribe(Observable.just(path).map {
            Luban.with(BaseApplication.INSTANCE).ignoreBy(500)
                .load(path).get()
        }.map {
            if (!it.isNullOrEmpty()) it[0]
            else throw NullPointerException("压缩图片失败")
        }.flatMap {
            val part: MultipartBody.Part = MultipartBody.Part.createFormData(
                "file", path, it.asRequestBody("image/*".toMediaType())
            )
            apiService.uploadPicture(part)
        }, HttpServiceSubscribe(listener))

    /**
     * 获取配置
     * */
    fun configValue(name: String, listener: SubscribeListener<ConfigResponse>): Disposable =
        subscribe(
            apiService.configValue(BaseApplication.userToken(), name),
            HttpServiceSubscribe(listener)
        )

    /**
     * 获取文章
     * */
    fun getArticle(id: String, listener: SubscribeListener<ArticleResponse>): Disposable =
        subscribe(
            apiService.getArticle(BaseApplication.userToken(), id),
            HttpServiceSubscribe(listener)
        )
}